import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { UIModifyInfo } from "./ui-modify-info.class";


@Injectable()
export class UIModifyService {

  constructor(private _http: Http) {
  }

  getUserInfo(url): Promise<any> {
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});

    return this._http.post(url,{}, options).toPromise()
      .then(this.extractData)
      .catch(this.handleError);
  }

  getUserInfoOfCompany(url: string, ids: string): Promise<any> {
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});

    return this._http.post(url, JSON.stringify({'ids': ids}), options).toPromise()
      .then(this.extractData)
      .catch(this.handleError);
  }

  getUserList(url): Promise<any> {
    return this._http.post(url,{}).toPromise()
      .then(this.extractData)
      .catch(this.handleError);
  }

  submit(url: string, uiModifyInfo: any): Promise<any> {
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});

    // const body = new URLSearchParams();
    // Object.keys(uiModifyInfo).forEach(key => {
    //   body.set(key, uiModifyInfo[key]);
    // });

    return this._http.post(url, JSON.stringify(uiModifyInfo), options).toPromise()
      .then(this.extractData)
      .catch(this.handleError);
  }

  extractData(res: Response) {
    let body = res.json();
    return body || {};
  }

  handleError(error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
      if (error.status > 200) {
        errMsg = '网络异常';
      } else {
        errMsg = '无法获取数据';
      }
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    return Promise.reject(errMsg);
  }
}
